package sms.util;

import com.alibaba.excel.EasyExcel;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

public class ExcelUtils {

    // 读取Excel文件到对象列表（使用EasyExcel）
    public static <T> List<T> readExcel(MultipartFile file, Class<T> clazz) {
        try {
            return EasyExcel.read(file.getInputStream())
                    .head(clazz)
                    .sheet()
                    .doReadSync();
        } catch (IOException e) {
            throw new RuntimeException("Excel解析失败", e);
        }
    }

    // 导出数据到Excel（HTTP响应流）
    public static void exportExcel(HttpServletResponse response,
                                   List<?> data,
                                   String fileName,
                                   Class<?> clazz) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            EasyExcel.write(response.getOutputStream(), clazz).sheet("Sheet1").doWrite(data);
        } catch (IOException e) {
            throw new RuntimeException("Excel导出失败", e);
        }
    }
}
